package com.charactereducation.webcore.controller;

import com.charactereducation.tools.json.JsonHandler;
import com.charactereducation.tools.myRunTime.MyRunTimeExcption;
import com.charactereducation.tools.result.ReturnCode;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Baggio on 2018-6-22.
 */
public class BaseController {
    protected  Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    @Autowired
    protected HttpSession session;


    protected Map<String, String> showRequestParameters() {

        Enumeration<?> paramNames = request.getParameterNames();
        Map<String, String> map = new HashMap<String, String>();
        while (paramNames.hasMoreElements()) {

            String paramName = paramNames.nextElement().toString();
            String paramValue = request.getParameter(paramName);
            map.put(paramName, paramValue);
            System.out.println(paramName + "[:]" + paramValue);
        }



        return map;
    }


    protected Object json2Obj(Type clazz) {
        String str, wholeStr = "";
        try {
            BufferedReader br = request.getReader();

            while ((str = br.readLine()) != null) {
                wholeStr += str;
            }
            logger.info(wholeStr);
        } catch (IOException e) {
            throw new MyRunTimeExcption(ReturnCode.NET_ERRO);
        }
        return JsonHandler.json2Obj(wholeStr, clazz);
    }

    protected <T> T json2List(TypeToken<T> t) {
        String str, wholeStr = "";
        try {
            BufferedReader br = request.getReader();

            while ((str = br.readLine()) != null) {
                wholeStr += str;
            }
            logger.info("===========================>>>>>>>>>>>>>>>>>>>>>wholeStr>>>>>>>>>>>>>>>>>>>>>>>");
            logger.info(wholeStr);
            logger.info("===========================>>>>>>>>>>>>>>>>>>>>>wholeStr>>>>>>>>>>>>>>>>>>>>>>>");
        } catch (IOException e) {
            throw new MyRunTimeExcption(ReturnCode.NET_ERRO);
        }
        return JsonHandler.json2ObjList(wholeStr, t);
    }
}
